package com.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 多线程安全
public class SecurityJuc {
    public static Integer stock = 10000;
    static class StockRunnable implements Runnable {

        @Override
        public synchronized void run() {
            if(stock > 0) {
                stock--;
            }
            System.out.println(Thread.currentThread().getName() + "thread:" + stock);
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        StockRunnable task = new StockRunnable();

        for (int i = 0; i < 1000; i++) {
            executorService.execute(task);
        }
        // 等待线程结束 停止
        executorService.shutdown();
        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
            System.out.println(stock);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
